﻿using LNBMS.DAL.PetaPoco;
using LNBMS.Entity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace LNBMS.DAL
{
    public class TownDAL
    {
        private Database _db = new Database(ConfigurationManager.ConnectionStrings["npgSqlStr"].ConnectionString, "Npgsql");

        #region 增删改查
        /// <summary>
        /// 增加一条数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public bool Insert(Town entity)
        {
            bool isOk = _db.Insert(entity) != null ? true : false;
            return isOk;
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public bool Update(Town entity)
        {
            bool isOk = _db.Update(entity) > 0 ? true : false;
            return isOk;
        }
        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <param name="KeyValue">主键</param>
        /// <returns></returns>
        public bool Delete(string KeyValue)
        {
            bool isOk = _db.Delete<Town>(KeyValue) == 1 ? true : false;
            return isOk;
        }
        /// <summary>
        /// 根据一个主键得到一个实体
        /// </summary>
        /// <param name="KeyValue"></param>
        /// <returns></returns>
        public Town GetEntity(string KeyValue)
        {
            try
            {
                return _db.SingleOrDefault<Town>(string.Format("SELECT * FROM \"Town\" WHERE townid='{0}'", KeyValue));
            }
            catch (System.InvalidOperationException)
            {
                return null;
            }
        }
        #endregion

        /// <summary>
        /// 根据sql查找
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<Town> GetListBySql(string query)
        {
            return new List<Town>(GetListBySql(query, null));
        }
        /// <summary>
        /// 根据sql查找
        /// </summary>
        /// <param name="query"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<Town> GetListBySql(string query, string[] param)
        {
            return new List<Town>(_db.Query<Town>(query, param));
        }
    }
}
